package m3;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.Scanner;

public class Producer {
    public static void main(String[] args) throws MQClientException {

        // 创建事务消息生产者实例
        TransactionMQProducer t = new TransactionMQProducer("producerGroup3");
        //设置name server
        t.setNamesrvAddr("192.168.64.141:9876");
        //设置事务消息监听器
        t.setTransactionListener(new TransactionListener() {
            // 执行本地事务
            @Override
            public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
                System.out.println("执行本地事务，业务参数:"+arg);
                if (Math.random()<0.5){
                    System.out.println("事务执行成功，向Rocketmq服务器提交消息");
                    return LocalTransactionState.COMMIT_MESSAGE;// 成功
                }else {
                    System.out.println("事务执行失败，向Rocketmq服务器回滚消息、撤回消息");
                    return LocalTransactionState.ROLLBACK_MESSAGE;// 失败回滚
                }

//                return LocalTransactionState.UNKNOW;//执行本地事务的方法中一般不会出现未知状态
            }
            //处理Rocketmq的事务状态回查
            @Override
            public LocalTransactionState checkLocalTransaction(MessageExt msg) {
                return null;
            }
        });

        //启动
        t.start();
        //发送事务消息,会触发执行事务消息监听器执行本地事务
        while (true){
            System.out.println("输入消息");
            String s = new Scanner(System.in).nextLine();
            Message msg = new Message("Topic3", s.getBytes());
//            t.sendMessageInTransaction(msg, 触发监听器执行本地事务时，向他传递的业务数据参数);
//            t.sendMessageInTransaction(msg,"假的业务数据" );
            t.sendMessageInTransaction(msg, "假的业务数据");
        }
    }


}
